from django.utils.safestring import mark_safe
from django.urls import reverse
from stark.service.s1 import StarkHandler, choice_display
from app_main.forms.for_stark import CustomerPrivateModelForm


class CustomerPrivateHandler(StarkHandler):

    def follow_display(self, obj=None, is_head=None):
        if is_head:
            return '跟进'

        re_url = reverse('stark:app_main_followrecord_list', args=(obj.id,))
        return mark_safe('<a target="blank" href="%s">跟进记录</a>' % re_url)

    def display_pay_record(self, obj=None, is_head=None):
        if is_head:
            return '缴费'

        re_url = reverse('stark:app_main_paymentrecord_list', args=(obj.id,))
        return mark_safe('<a target="blank" href="%s">缴费记录</a>' % re_url)

    list_display = [
        StarkHandler.display_checkbox,
        'name',
        'contact',
        choice_display('状态', 'status'),
        display_pay_record,
        follow_display,
        StarkHandler.display_edit,
        StarkHandler.display_del
    ]

    model_form_class = CustomerPrivateModelForm

    def get_query_set(self, request, *args, **kwargs):  # 获取当前登录销售的私有用户
        current_user_id = request.session['user_info']['id']
        first_q_set = self.model_class.objects.filter(consultant_id=current_user_id)
        return first_q_set

    def save(self, request, form_obj, is_update, *args, **kwargs):
        if not is_update:
            current_user_id = request.session['user_info']['id']
            form_obj.instance.consultant_id = current_user_id
        form_obj.save()

    def multi_remove_customer(self, request, *args, **kwargs):  # 批量移除到公户
        current_user_id = request.session['user_info']['id']
        id_list = request.POST.getlist('cb')
        self.model_class.objects.filter(id__in=id_list, consultant_id=current_user_id).update(consultant=None)

    multi_remove_customer.text = '批量移除到公户'

    action_list = [multi_remove_customer]
